package middleware.p2p.replication;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.Singleton;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

/**
 * Session Bean implementation class ReplicaTransactionCache
 */
@Singleton(name="ReplicaCache")
@TransactionManagement(TransactionManagementType.BEAN)
public class ReplicaTransactionCache implements ReplicaTransactionCacheLocal {
	private Map<String,ReplicaCacheEntry> cacheMap;
    /**
     * Default constructor. 
     */
    public ReplicaTransactionCache() {
        super();
        this.cacheMap=new HashMap<String,ReplicaCacheEntry>();
    }
    @Override
    public boolean storeReplicaEntry(String transId,String cid,String content,ReplicaAction action) {
    	ReplicaCacheEntry entry=new ReplicaCacheEntry(cid, content,action);
    	this.cacheMap.put(transId, entry);
    	return true;
    }
    @Override
    public boolean registerTempFile(String transId,File tempFile) {
    	if (this.cacheMap.containsKey(transId)) {
    		this.cacheMap.get(transId).setTempFile(tempFile);
    		return true;
    	} else {
    		return false;
    	}
    }
    @Override
    public boolean deleteReplicaEntry(String transId) {
    	if (this.cacheMap.containsKey(transId)) {
    		ReplicaCacheEntry entry=this.cacheMap.get(transId);
    		File tFile=entry.getTempFile();
    		if (tFile!=null) {
    			tFile.delete();
    		}
    		this.cacheMap.remove(transId);
    		return true;
    	} else {
    		return false;
    	}
    }
    @Override
    public ReplicaCacheEntry getReplicaEntry(String transId) {
    	if (this.cacheMap.containsKey(transId)) {
    		return this.cacheMap.get(transId);
    	} else {
    		return null;
    	}
    }
}
